package com.atguigu.gmall.order.receiver;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.payment.client.PaymentFeignClient;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

@Component
public class OrderReceiver {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentFeignClient paymentFeignClient;

    //  监听的消息
    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void cancelOrder(Long orderId, Message message, Channel channel) {
        //  判断当前订单Id 不能为空
        try {
            //  获取到消息并判断
            if (orderId!=null){
                //  取消订单业务！ 判断这个订单id 是否存在。
                OrderInfo orderInfo = orderService.getById(orderId);
                if (orderInfo!=null && "UNPAID".equals(orderInfo.getOrderStatus()) && "UNPAID".equals(orderInfo.getProcessStatus())){
                    //  未支付.... 本质更改订单状态！
                    //  orderService.execExpiredOrder(orderId);
                    PaymentInfo paymentInfo = this.paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                    //  判断是否有paymentInfo
                    if (paymentInfo!=null && "UNPAID".equals(paymentInfo.getPaymentStatus())){
                        //  还需要判断用户是否扫描二维码!
                        Boolean result = this.paymentFeignClient.checkPayment(orderId);
                        //  result = true; 表示扫描了二维码.orderInfo，paymentInfo,可能还需要关闭aliPay！
                        if (result){
                            //  直接调用关闭方法.   扫描了二维码有交易记录，未付款才能关闭!
                            Boolean flag = this.paymentFeignClient.closePay(orderId);
                            //  flag = true; 关闭成功.
                            if (flag){
                                this.orderService.execExpiredOrder(orderId,"2");
                            }else {
                                //  flag = false; 关闭失败,意味着在最后关键时刻这个哥们付款了.
                            }
                        }else {
                            //   result = false; 表示没有扫描二维码. 一定要关闭，orderInfo，paymentInfo!
                            this.orderService.execExpiredOrder(orderId,"2");
                        }
                    }else {
                        //  一定要关闭orderInfo！
                        this.orderService.execExpiredOrder(orderId,"1");
                    }
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        //  手动确认消息 如果不确认，有可能会到消息残留。
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void paymentPay(Long orderId, Message message ,Channel channel){

        try {
            //  判断
            if(orderId!=null){
                //  更新订单状态.
                this.orderService.updateOrderStatus(orderId, ProcessStatus.PAID);
                //  发送消息给库存系统，通知减库存.
                this.orderService.sendOrderStatus(orderId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  消息确认:
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


    //  监听支付成功之后，发送过来的消息.
   /* @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void payment(Long orderId, Message message, Channel channel) {
        try {
            if (orderId != null) {
                //修改状态
                orderService.updateOrderStatus(orderId, ProcessStatus.PAID);
                //减库存
                orderService.sendOrderStatus(orderId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  消息确认:
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
*/
    //监听减库存
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = {MqConst.ROUTING_WARE_ORDER}
    ))
    public void wartOrder(String wartJson, Message message, Channel channel) {
        try {
            if (!StringUtils.isEmpty(wartJson)) {
                //转换成map
                Map map = JSONObject.parseObject(wartJson, Map.class);
                String orderId = (String) map.get("orderId");
                String status = (String) map.get("status");
                if ("DEDUCTED".equals(status)) {
                    orderService.updateOrderStatus(Long.parseLong(orderId), ProcessStatus.WAITING_DELEVER);
                } else {
                    //减库存异常
                    orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.STOCK_EXCEPTION);
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        //手动确认消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

    }
}
